package cn.edu.scau.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.scau.bean.ResultBean;
import cn.edu.scau.config.Audience;
import cn.edu.scau.entity.Manager;
import cn.edu.scau.entity.Nurse;
import cn.edu.scau.entity.RecoveryTrack;
import cn.edu.scau.entity.WorkPlan;
import cn.edu.scau.service.CustomerService;
import cn.edu.scau.service.ManagerService;
import cn.edu.scau.service.NurseService;
import cn.edu.scau.service.WorkPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "工作计划控制器")
@RestController
@Controller
@RequestMapping("workPlan")
public class WorkPlanController {
	@Autowired
	WorkPlanService workPlanService;
	@Autowired
	NurseService nurseService;
	@Autowired
	ManagerService managerService;
	@Autowired
	private Audience audience;//?
	
    /**
     * 显示所有工作计划信息
     * @return
     */
	@ApiOperation(value = "显示所有信息页面:数据存储在hospital中")
    @GetMapping(value = "/list")
    public ResultBean list(){
		List<WorkPlan> workPlans = workPlanService.selectAll();
        System.out.println("请求所有登记数据："+workPlans);
        ResultBean r = new ResultBean(200,true,"查询所有工作计划成功",workPlans);
        return r;
	}
	
	@ApiOperation(value = "显示所有信息页面:数据存储在hospital中")
    @GetMapping(value = "/nurseList/{userAccount}")
    public ResultBean nurseList(@PathVariable("userAccount") String userAccount){
		Manager manager = managerService.selectByUserAccount(userAccount);
		Nurse nurse = nurseService.selectByUserId(manager.getUserId());
		List<WorkPlan> workPlans = workPlanService.selectByNurseID(nurse.getNurseid());
        System.out.println("请求所有登记数据："+workPlans);
        ResultBean r = new ResultBean(200,true,"查询所有工作计划成功",workPlans);
        return r;
	}
	
	
	/**
	 * 根据主键查询工作计划
	 * @param nurseID
	 * @param workDate
	 * @return
	 */
	@GetMapping(value = "/{id}/{date}")
	public ResultBean findByID(@PathVariable("id") Integer nurseID,@PathVariable("date") Date workDate){
		ResultBean r = null;
		WorkPlan workPlans = workPlanService.selectByPrimaryKey(workDate, nurseID);
		if(workPlans==null) {
			r = new ResultBean(500,false,"查询工作计划失败",null);
		}
		else {
			r = new ResultBean(200,true,"查询工作计划成功",workPlans);
		}
		return r;
	}
	
	/**
	 * 修改工作计划信息
	 * @param nurseID
	 * @param workDate
	 * @param workPlan
	 * @param bindingResult
	 * @return
	 */
	@PutMapping(value = "/update/{id}/{date}")
	public ResultBean update(@PathVariable("id") Integer nurseID,@PathVariable("date") Date workDate,@Validated WorkPlan workPlan, BindingResult bindingResult) {
		ResultBean r = null;
		if(bindingResult.hasErrors()){
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
            ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            return r;
        }
		
		Nurse nurse=nurseService.selectByPrimaryKey(workPlan.getNurseID());
        if(nurse==null) {
        	r =new ResultBean(5005,false,"护士编号不存在或无效",null);
        	return r;
        }
        else {
        	if(nurse.getNurseuseflag()==false) {
        		r =new ResultBean(5005,false,"护士编号不存在或无效",null);
        		return r;
        	}
        }//外键约束
		
        if(workPlan.getWorkDate().compareTo(workDate)!=0||workPlan.getNurseID().intValue()!=nurseID.intValue()) {
        	if(workPlanService.selectByPrimaryKey(workPlan.getWorkDate(), workPlan.getNurseID())!=null) {
            	r =new ResultBean(5005,false,"已经有对应日期和护士的工作安排",null);
            	return r;
            }
        }
        
        
		boolean flag = workPlanService.update(workPlan);
		if(flag){
            r =new ResultBean(200,true,"修改成功",null);
        }else
        {
            r =new ResultBean(5005,false,"修改失败",null);
        }
		return r;
	}
	
	
	/**
	 * 根据前端发来的护士编号检测该护士是否存在
	 * @param nurseid
	 * @return
	 */
	@GetMapping(value = "/checkNurseID/{nurseid}")
	public ResultBean checkNurseID(@PathVariable("nurseid") Integer nurseid){
		ResultBean r = null;
		Nurse nurse = nurseService.selectByPrimaryKey(nurseid);
		if(nurse==null) { 
			r = new ResultBean(500,false,"找不到编号为"+nurseid+"的护士，请确认后重新输入",null);
			return r;
		}
		else {
			if(nurse.getNurseuseflag()==false) {
				r = new ResultBean(500,false,"已经没有编号为"+nurseid+"的护士，请确认后重新输入",null);
				return r;
			}
		}
		r = new ResultBean(200,true,"护士编号检查成功",nurse.getNursename());
		return r;
	}
	
	
	/**
	 * 新增工作计划
	 * @param workPlan
	 * @param bindingResult
	 * @return
	 */
	@PostMapping(value = "/insert")
	public ResultBean insert(@Validated WorkPlan workPlan, BindingResult bindingResult) {
		ResultBean r = null;
        if(bindingResult.hasErrors()){
            StringBuffer msg = new StringBuffer();
            for (FieldError f:bindingResult.getFieldErrors()
                 ) {
                msg.append(f.getField()+":"+f.getDefaultMessage()+"\n");
            }
            r = new ResultBean(5006,false,msg.toString(),null);
            return r;
        }
        
        Nurse nurse=nurseService.selectByPrimaryKey(workPlan.getNurseID());
        if(nurse==null) {
        	r =new ResultBean(5005,false,"护士编号不存在或无效",null);
        	return r;
        }
        else {
        	if(nurse.getNurseuseflag()==false) {
        		r =new ResultBean(5005,false,"护士编号不存在或无效",null);
        		return r;
        	}
        }//外键约束
        
        if(workPlanService.selectByPrimaryKey(workPlan.getWorkDate(), workPlan.getNurseID())!=null) {
        	r =new ResultBean(5005,false,"已经有对应日期和护士的工作安排",null);
        	return r;
        }
        
        boolean flag = workPlanService.insert(workPlan);
        if(flag){
        	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            r =new ResultBean(200,true,"成功护士编号为:"+workPlan.getNurseID()+"\n时间为"+sdf.format(workPlan.getWorkDate())+"的工作计划",null);
        }else
        {
            r =new ResultBean(5005,false,"增加工作计划失败",null);
        }
        return r;
	}
	
	/**
	 * 根据主键删除工作计划
	 * @param nurseID
	 * @param workDate
	 * @return
	 */
	@DeleteMapping(value = "/delete/{id}/{date}")
	public ResultBean delete(@PathVariable("id") Integer nurseID,@PathVariable("date") Date workDate){
		ResultBean r = null;
        boolean flag = workPlanService.delete(workDate, nurseID);
        if(flag){
            r =new ResultBean(200,true,"删除成功",null);
        }else
        {
            r =new ResultBean(5005,false,"删除失败",null);
        }
        return r;
	}
	
	/**
	 * 根据工作计划日期、护士编号、护士名组合查询
	 * @param workDate
	 * @param nurseID
	 * @param nurseName
	 * @return
	 * @throws ParseException
	 */
	@GetMapping(value = "/find")
    public ResultBean find(String workDate,Integer nurseID,String nurseName) throws ParseException{
		Date date = null;
		if(!StringUtils.isBlank(workDate)){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.parse(workDate);
        }
		List<WorkPlan> recoveryTracks = workPlanService.find(date, nurseID, nurseName);
        ResultBean r = new ResultBean(200,true,"组合模糊查询工作计划成功",recoveryTracks);
		return r;
	}
	
	@GetMapping(value = "/nurseFind/{userAccount}")
    public ResultBean find(@PathVariable("userAccount") String userAccount,String workDate,Integer nurseID,String nurseName) throws ParseException{
		Manager manager = managerService.selectByUserAccount(userAccount);
		Nurse nurse = nurseService.selectByUserId(manager.getUserId());
		Date date = null;
		if(!StringUtils.isBlank(workDate)){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.parse(workDate);
        }
		List<WorkPlan> recoveryTracks = workPlanService.findWithNurseID(date, nurse.getNurseid(), nurseName);
        ResultBean r = new ResultBean(200,true,"组合模糊查询工作计划成功",recoveryTracks);
		return r;
	}
}
